<template>
    <div v-if="isShowEdit" class="rich-text-editor" :style="{ height: height + 'px' }">
        <div ref="toolbarRef" class="editor-toolbar" />
        <div ref="editorRef" class="editor-content" />
    </div>
</template>

<script setup lang="ts">
import { ref, onBeforeUnmount, shallowRef, onMounted, nextTick } from 'vue'
import '@wangeditor/editor/dist/css/style.css'
import type { IToolbarConfig } from '@wangeditor/editor'

const isShowEdit = ref(false)
onMounted(() => {
    isShowEdit.value = true
})

// Props 定义
interface Props {
    modelValue?: string
    placeholder?: string
    height?: number
    readonly?: boolean
}

// Emits 定义
interface Emits {
    (e: 'update:modelValue', value: string): void
}

const props = withDefaults(defineProps<Props>(), {
    modelValue: '',
    placeholder: '请输入内容...',
    height: 300,
    readonly: false
})

const emit = defineEmits<Emits>()

// DOM 引用
const toolbarRef = ref<HTMLElement | null>(null)
const editorRef = ref<HTMLElement | null>(null)

// 编辑器实例类型
interface EditorInstance {
    getHtml: () => string
    setHtml: (html: string) => void
    disable: () => void
    enable: () => void
    destroy: () => void
    focus: () => void
    blur: () => void
    on: (event: string, callback: () => void) => void
}

// 编辑器实例
const editorInstance = shallowRef<EditorInstance | null>(null)

// 初始化编辑器
const initEditor = async () => {
    if (!import.meta.client || !toolbarRef.value || !editorRef.value) return

    try {
        // 动态导入 wangEditor5
        const { createEditor, createToolbar } = await import('@wangeditor/editor')

        // 清理可能存在的旧编辑器实例
        if (editorInstance.value) {
            editorInstance.value.destroy()
            editorInstance.value = null
        }

        // 确保 DOM 元素为空
        editorRef.value.innerHTML = ''
        toolbarRef.value.innerHTML = ''

        // 编辑器配置
        const editorConfig = {
            placeholder: props.placeholder,
            readOnly: props.readonly,
            autoFocus: false,
            scroll: true,
            maxLength: 10000,
            MENU_CONF: {
                // 配置颜色
                color: {
                    colors: [
                        '#000000', '#ffffff', '#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff', '#00ffff',
                        '#c0c0c0', '#808080', '#800000', '#808000', '#008000', '#800080', '#008080', '#000080'
                    ]
                },
                // 配置字体
                fontFamily: {
                    fontFamilyList: [
                        '黑体', '楷体', '仿宋', '宋体', '微软雅黑', 'Arial', 'Tahoma', 'Verdana'
                    ]
                },
                // 配置字号
                fontSize: {
                    fontSizeList: ['12px', '13px', '14px', '15px', '16px', '19px', '22px', '24px', '32px', '48px']
                },
                // 配置无序列表
                bulletedList: {
                    type: 'bulleted-list'
                },
                // 配置有序列表
                numberedList: {
                    type: 'numbered-list'
                }
            }
        }

        // 创建编辑器
        const editor = createEditor({
            selector: editorRef.value,
            html: props.modelValue || '<p><br></p>',
            config: editorConfig,
            mode: 'default'
        })

        // 工具栏配置
        const toolbarConfig: Partial<IToolbarConfig> = {
            toolbarKeys: [
                'headerSelect', 'blockquote',
                '|',
                'bold', 'underline', 'italic', 'color', 'bgColor', '|',
                'fontSize', 'fontFamily', 'lineHeight', '|',
                'bulletedList', 'numberedList', '|',
                'fullScreen'
            ]
        }

        // 创建工具栏
        createToolbar({
            editor,
            selector: toolbarRef.value,
            config: toolbarConfig,
            mode: 'default'
        })

        // 保存编辑器实例
        editorInstance.value = editor

        // 监听内容变化
        editor.on('change', () => {
            const html = editor.getHtml()
            emit('update:modelValue', html)
        })

    } catch (error) {
        console.error('wangEditor5 初始化失败：', error)
    }
}

// 组件挂载时初始化编辑器
onMounted(() => {
    nextTick(() => {
        if (isShowEdit.value) {
            // 添加延迟确保 DOM 完全渲染
            setTimeout(() => {
                initEditor()
            }, 100)
        }
    })
})

// 监听 isShowEdit 变化
watch(isShowEdit, (newValue) => {
    if (newValue) {
        nextTick(() => {
            // 添加延迟确保 DOM 完全渲染
            setTimeout(() => {
                initEditor()
            }, 100)
        })
    }
})

// 监听 props 变化
watch(() => props.modelValue, (newValue) => {
    if (editorInstance.value && editorInstance.value.getHtml() !== newValue) {
        editorInstance.value.setHtml(newValue || '')
    }
})

watch(() => props.readonly, (newReadonly) => {
    if (editorInstance.value) {
        editorInstance.value.disable()
        if (!newReadonly) {
            editorInstance.value.enable()
        }
    }
})

// 组件销毁前清理编辑器
onBeforeUnmount(() => {
    if (editorInstance.value) {
        editorInstance.value.destroy()
        editorInstance.value = null
    }
})

// 暴露方法给父组件
defineExpose({
    getContent: () => editorInstance.value?.getHtml() || '',
    setContent: (content: string) => {
        if (editorInstance.value) {
            editorInstance.value.setHtml(content)
        }
    },
    focus: () => editorInstance.value?.focus(),
    blur: () => editorInstance.value?.blur(),
    getEditor: () => editorInstance.value
})
</script>

<style scoped>
.rich-text-editor {
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    overflow: hidden;
    font-size: 14px;
}

/* wangEditor5 工具栏样式 */
.editor-toolbar {
    border-bottom: 1px solid #d9d9d9;
    min-height: 40px;
}

/* wangEditor5 编辑器内容区样式 */
.editor-content {
    height: calc(100% - 40px);
    overflow-y: auto;
    min-height: 200px;
}

/* 深度样式修改 */
:deep(.w-e-text-container) {
    height: 100% !important;
    min-height: 200px;
}

:deep(.w-e-scroll) {
    height: 100% !important;
    min-height: 200px;
}

:deep(.w-e-text) {
    min-height: 200px;
}

:deep(.w-e-text-placeholder) {
    color: #bfbfbf;
}

:deep(.w-e-text-container .w-e-text) {
    padding: 12px;
    line-height: 1.6;
}

/* 自定义工具栏按钮样式 */
:deep(.w-e-toolbar) {
    background: #fafafa;
    border-bottom: 1px solid #d9d9d9;
}

:deep(.w-e-toolbar .w-e-bar-item) {
    border-radius: 4px;
    margin: 2px;
}

:deep(.w-e-toolbar .w-e-bar-item:hover) {
    background: #f0f0f0;
}

:deep(.w-e-toolbar .w-e-bar-item.w-e-bar-item-active) {
    background: #1890ff;
    color: white;
}

/* 编辑器内容样式 */
:deep(.w-e-text-container) {
    background: white;
}

/* 表格样式 */
:deep(.w-e-text table) {
    border-collapse: collapse;
    width: 100%;
    margin: 8px 0;
}

:deep(.w-e-text table td) {
    border: 1px solid #ccc;
    padding: 8px;
    min-width: 100px;
}

/* 代码块样式 */
:deep(.w-e-text pre) {
    background: #f5f5f5;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    padding: 12px;
    margin: 8px 0;
    overflow-x: auto;
}

/* 引用块样式 */
:deep(.w-e-text blockquote) {
    border-left: 4px solid #1890ff;
    padding-left: 12px;
    margin: 8px 0;
    color: #666;
    background: #f9f9f9;
}

/* 链接样式 */
:deep(.w-e-text a) {
    color: #1890ff;
    text-decoration: none;
}

:deep(.w-e-text a:hover) {
    text-decoration: underline;
}
</style>